from __future__ import annotations
from typing import Optional, Dict, Any, List
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.types import JSON
from extensions import db
from datetime import datetime
from sqlalchemy import func

class Order(db.Model):
    """订单模型"""
    __tablename__ = 'orders'

    # 自增主键ID，系统内部使用的唯一标识
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
    # 订单唯一标识符，使用UUID格式作为订单的唯一标识，用于系统间数据关联
    order_id: Mapped[str] = mapped_column(db.String(36), unique=True, index=True)
    # 所属店铺ID，标识订单所属的店铺
    store_id: Mapped[str] = mapped_column(db.String(36), nullable=False)
    # 客户ID，标识下单的客户
    customer_id: Mapped[str] = mapped_column(db.String(36), nullable=False)
    # 订单项目明细，JSON格式，包含服务项目、价格、数量等详细信息
    items: Mapped[Dict[str, Any]] = mapped_column(JSON, nullable=False)
    # 订单总金额，订单中所有服务项目的总价
    total_amount: Mapped[float] = mapped_column(db.Float, nullable=False)
    # 实付金额，客户实际支付的金额，默认0
    actual_amount: Mapped[float] = mapped_column(db.Float, nullable=False, default=0.0)
    # 订单状态，标识订单的处理阶段，如：pending-待支付，completed-已完成等
    status: Mapped[str] = mapped_column(db.String(20), nullable=False, default='pending')
    # 支付方式，客户选择的支付方式，如：现金、微信、支付宝等
    payment_method: Mapped[Optional[str]] = mapped_column(db.String(20))
    # 关联的卡包ID，可选字段
    card_package_id: Mapped[Optional[str]] = mapped_column(db.String(36))
    # 订单备注信息，存储订单的特殊要求或补充说明
    remarks: Mapped[Optional[str]] = mapped_column(db.Text)
    # 客户手机号，可选字段
    phone: Mapped[Optional[str]] = mapped_column(db.String(20))
    # 订单创建时间，订单首次创建的时间戳
    created_at: Mapped[datetime] = mapped_column(
        db.DateTime, 
        server_default=func.now(),  # 使用数据库当前时间
        default=datetime.now        # 使用Python系统时间作为后备
    )
    updated_at: Mapped[datetime] = mapped_column(
        db.DateTime, 
        server_default=func.now(),  # 使用数据库当前时间
        default=datetime.now,       # 使用Python系统时间作为后备
        onupdate=datetime.now       # 更新时使用Python系统时间
    )
    # 软删除标记，True表示已删除，False表示正常
    is_deleted: Mapped[bool] = mapped_column(db.Boolean, default=False)
    
    # 关联关系定义
    # 店铺和客户关联通过ID字段进行手动查询，不使用外键约束

    def __init__(self, order_id: str, store_id: str, customer_id: str, items: Dict[str, Any], 
                 total_amount: float, status: str = 'pending', 
                 payment_method: Optional[str] = None, remarks: Optional[str] = None, 
                 actual_amount: float = 0.0, phone: Optional[str] = None,
                 card_package_id: Optional[str] = None) -> None:
        self.phone = phone
        self.order_id = order_id
        self.store_id = store_id
        self.customer_id = customer_id
        self.items = items
        self.total_amount = total_amount
        self.actual_amount = actual_amount
        self.status = status
        self.payment_method = payment_method
        self.remarks = remarks
        self.card_package_id = card_package_id

    def to_dict(self) -> Dict[str, Any]:
        """将模型转换为字典"""
        return {
            'id': self.id,
            'order_id': self.order_id,
            'store_id': self.store_id,
            'customer_id': self.customer_id,
            'items': self.items,
            'total_amount': self.total_amount,
            'actual_amount': self.actual_amount,
            'status': self.status,
            'payment_method': self.payment_method,
            'card_package_id': self.card_package_id,
            'remarks': self.remarks,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'phone': self.phone,
        }